require 'table'

class Stock < ActiveRecord::Base
  validates_presence_of :company_name, :stock_no

  @@en2cn = {
      :company_name=>"公司",
      :stock_no=>"股票代码",
      :abbr=>"缩写"
  }

  def self.en2cn
    @@en2cn
  end

  def self.find_all_from_sina
    stocks = []
    #取上证公司名称及代号
    100.times do |i|
      break unless grab_stocks! "http://stock.finance.sina.com.cn/stock/quote/sha#{i}.html", stocks
    end

    #取深证公司名称及代号
    100.times do |i|
      break unless grab_stocks! "http://stock.finance.sina.com.cn/stock/quote/sza#{i}.html", stocks
    end
    return stocks
  end
  
  #净利润率
  def net_profit_margin
    @profit_statement.net_profit_margin if @profit_statement
  end
  
  #毛利润率
  def gross_profit_margin
    @profit_statement.gross_profit_margin if @profit_statement
  end
  
  #经营利润率
  def operating_profit_margin
    @profit_statement.operating_profit_margin if @profit_statement
  end
  
  #资产周转率
  def assert_turnover
    @profit_statment.main_operating_revenue.to_f / @balance_sheet.total_assets.to_f if @profit_statment && @balance_sheet
  end
  
  #股东权益比
  def equity_ratio
    @balance_sheet.total_shareholders_equity.to_f / @balance_sheet.total_assets.to_f if @balance_sheet
  end
  
  #财务杠杆比例
  def financial_leverage_ratio
    1 / (1 - equity_ratio) * 100
  end
  
  #净资产收益率
  def roe
    @profit_statement.net_profit.to_f / @balance_sheet.total_shareholders_equity.to_f * 100 if @balance_sheet && @profit_statement
  end
  
  #自由现金流
  def free_cash_flow
    o_cash_flow = @cash_flow_statement.operating_activities_generated_net_cash_flow
    i_cash_fow = @cash_flow_statement.investment_activities_generated_net_cash_flow
    o_cash_flow - i_cash_flow if @cash_flow_statement
  end
  
  def cash_in_main_operating_revenue
    free_cash_flow.to_f / @balance_sheet.total_assets.to_f if @balance_sheet
  end

  #主营业务现金含量
  def cash_in_net_profit
    free_cash_flow.to_f / @profit_statement.net_profit.to_f if @profit_statement
  end
  
  #净利润现金含量
  def focus_on(report_date)
    conditions = {:stock_no => stock_no, :report_date => report_date}
    @balance_sheet = BalanceSheet.find(:first, :conditions => conditions)
    @profit_statement = ProfitStatement.find(:first, :conditions => conditions)
    @cash_flow_statement = CashFlowStatement.find(:first, :conditions => conditions)
    return self
  end

  private
  def self.grab_stocks!(url, stocks, tryCount=10)
		table = nil
		tryCount.times do 
	    table = Table.new(:url=>url, :path=>"h2 ~ table tr")			
			break unless table.row_size < 1 || table.column_size < 0
		end
				
    return false if table.row_size < 1 || table.column_size < 0
    
    (table.row_size - 3).times do |r|
      stock_no = Iconv.conv("UTF-8", "GB2312", table[r+1][0])
      company_name = Iconv.conv("UTF-8", "GB2312", table[r+1][1])
      stocks << {:stock_no=>stock_no, :company_name=>company_name[3..-1]}
    end
    
  end
end
